package com.wenc.psi.fgmt;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SearchView;

import com.wenc.psi.R;
import com.wenc.psi.databinding.FragmentInventoryBinding;
import com.wenc.psi.rvAdapter.PartAdapter;
import com.wenc.psi.vmd.PartViewModel;

public class InventoryFragment extends Fragment {

    FragmentInventoryBinding binding;
    private RecyclerView recyclerView;
    private PartAdapter partAdapter;
    private PartViewModel partViewModel;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_inventory, container, false);

        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // 初始化控件
        initView();
        // 获取ViewModel
        partViewModel = new ViewModelProvider(getActivity()).get(PartViewModel.class);
        // 对ViewModel的数据进行监听
        partViewModel.getPartLive().observe(getActivity(), parts -> {
            System.out.println("有变化");
            System.out.println(parts.get(0).toString());
            partAdapter.setPartList(parts);
            partAdapter.notifyDataSetChanged();
        });
    }
    // 初始化控件
    private void initView() {
        // 创建适配器
        partAdapter = new PartAdapter();
        // 设置布局
        binding.rvPart.setLayoutManager(new LinearLayoutManager(getActivity()));
        // 设置适配器
        binding.rvPart.setAdapter(partAdapter);
        // 清除按键测试
        binding.clear.setOnClickListener(v -> {
            System.out.println("点击clear");
            partViewModel.clear();
        });
        // 搜索框事件处理
        binding.searchPart.setOnCloseListener(new SearchView.OnCloseListener() {
            @Override
            public boolean onClose() {
                partViewModel.getAllPart();
                return false;
            }
        });
        // 搜索框事件处理
        binding.searchPart.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                // 模糊搜索数据
                partViewModel.getDataBySearch(newText);
                return false;
            }
        });
    }
}